package com.gzy.rpsm_property.config;

import com.gzy.rpsm_property.utils.TokenUtil;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

public class LoginInterceptor extends HandlerInterceptorAdapter {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
                             Object handler) throws Exception {
// 从HTTP请求头Header中获取携带的token信息
        String token = request.getHeader("Authorization");
// 校验token信息是否有效，并获取用户ID
        Integer userId = TokenUtil.validateTokenAndGetUserId(token);
        if(Optional.ofNullable(userId).isPresent()){//如果成功获取到了userId，则放行
            request.setAttribute("userId", userId); // 设置userId到request中，后续请求可直接获取
            return true;
        }else{//否则，返回403错误
            response.sendError(403,"Authorization无信息，未登录");
            return false;
        }
    }
}